package com.winit.cloudlink.mgmt.task;

import com.datastax.driver.core.DataType;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.data.cassandra.mapping.CassandraType;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Table(TaskPO.TABLE_TASK)
@Data
public class TaskPO {
    public static final String TABLE_TASK = "cloudlink_task"; // 任务表
    @PrimaryKey(value = "id")
    private String id;

    @Column(value = "name")
    private String name;

    @Column(value = "type")
    private String type;

    @Column(value = "status")
    private String status;

    @Column(value = "error")
    private String error;

    @Column(value = "created")
    private Date created;

    @Column(value = "started")
    private Date started;

    @Column(value = "ended")
    private Date ended;

    @CassandraType(type = DataType.Name.MAP, typeArguments = {DataType.Name.TEXT, DataType.Name.TEXT})
    @Column(value = "params")
    private Map<String, String> params = Maps.newHashMap();

    public static List<Task> fromPO(Iterable<TaskPO> sources) {
        if (sources == null || !sources.iterator().hasNext()) {
            return Lists.newArrayList();
        }
        List<Task> result = Lists.newArrayList();
        for (TaskPO source : sources) {
            result.add(fromPO(source));
        }
        return result;
    }

    public static Task fromPO(TaskPO source) {
        if (source == null) {
            return null;
        }
        Task target = new Task();
        BeanUtils.copyProperties(source, target);
        return target;
    }

    public static List<TaskPO> toPO(List<Task> sources) {
        if (CollectionUtils.isEmpty(sources)) {
            return Lists.newArrayList();
        }
        List<TaskPO> result = Lists.newArrayList();
        for (Task source : sources) {
            result.add(toPO(source));
        }
        return result;
    }


    public static TaskPO toPO(Task source) {
        if (source == null) {
            return null;
        }
        TaskPO target = new TaskPO();
        BeanUtils.copyProperties(source, target);
        return target;
    }

}
